/**
 * 房源管理
 */
define(function (require, exports, module) {
    require('authorize');
    var util = require('util');
    var ui = require('ui');
    var _ = require('underscore');
    var angular = require("angular");
    require("angular-route");
    require("angular-ui");
    require("angular-messages");
    var permission = require('permission');
    require('placeholder');
    require('service/ng_service/projectService');
    require('global');

    var api_prefix = G_CONFIG["api_prefix"] + "/qmyx/building-info/"; //api前缀


    require('./buildings_detail');
    require('./house_type');
    require('./sources_info');
    require('./project_info');
    require('./project_role');



    angular.module('app', ['ngRoute', 'ngMessages', 'ngUI','ngPlaceholder','ProjectService','buildingsDetail','houseType','sourcesInfo','projectInfo','projectRole'])
        .config(['$routeProvider', function ($routeProvider) {
            $routeProvider
                .when('/project_info', {templateUrl: 'inc/project_info.html'})
                .when('/project_role', {templateUrl: 'inc/project_role.html'})
                .when('/buildings_detail', {templateUrl: 'inc/buildings_detail.html',controller:'buildingsDetailCtl'})
                .when('/housetype_info', {templateUrl: 'inc/housetype_info.html',controller:'houseTypeCtl'})
                .when('/sources_info', {templateUrl: 'inc/sources_info.html',controller:'sourcesInfoCtl'})
                .otherwise({redirectTo: '/project_info'});
        }])
        .directive('ngCustomNumber',function(){
            return {
                require: 'ngModel',
                link: function (scope, elm, attrs, ctrl) {

                    elm.bind('keydown',function(e){
                        var keyCode = e.keyCode;

                        // Backspace键
                        if (keyCode == 8) return true

                        // 数字
                        if (keyCode >= 48 && keyCode <= 57 ) return true

                        // 小数字键盘
                        if (keyCode >= 96 && keyCode <= 105) return true

                        // .键 || 小数字.
                        if(keyCode == 190 || keyCode == 110) return true;

                        // < || >
                        if(keyCode == 38 || keyCode == 40)return true;

                        return false;
                    });
                    elm.bind('paste',function(e){
                        return false
                    });
                }
            }
        })
        .factory('manageService',['$q','$http',function($q,$http){
            return {
                hasFuncCodePermission : function(func,code){
                    var deferred = $q.defer();
                    permission.getData(function(data){
                        var functions = data.functions;
                        var has = _.find(functions,function(obj){ return obj.funcCode == func && obj.code == code;});
                        deferred.resolve(!!has);
                    });
                    return deferred.promise
                },
                getBuildingInfo:function(proj_id,scope){
                    var url = api_prefix + "get-building-info";
                    var data = {
                        proj_id : proj_id
                    };
                    util.myAjax({
                        url: url,
                        type: "get",
                        data:data,
                        success: function(json) {
                            if (json.retCode == 0) {
                                scope.$apply(function(){
                                    scope.building_id = json.data ? json.data.b_regbroker_building_infoId : "";
                                });

                            } else {
                                ui.showErrTip(json.errMsg);
                            }
                        }
                    });
                },
                getProjectList : function(){
                    return $http.get(G_CONFIG.api_prefix + 'project/project/get-all-auth-project-list',{params : {NEED_TOKEN: false}});
                },
                getProjInfo: function (data, search) {
                    search = (search || '') + '&rnd=' + (new Date()).getTime();
                    data = data || {};
                    data['params'] = data['params'] || {};
                    data['params']['NEED_TOKEN'] = false;
                    return $http.get('/api/index.php?r=project/project/get-project-info' + search, data);
                },
                checkHasApp:function(data,search){
                    search = (search || '') + '&rnd=' + (new Date()).getTime();
                    data = data || {};
                    data['params'] = data['params'] || {};
                    data['params']['NEED_TOKEN'] = false;
                    return $http.get('/api/index.php?r=common/my-applicationto-project/has-project-app' + search, data);
                }
            };
        }])
        .controller('MainController', ['$rootScope', '$scope', '$location','manageService',
            function ($rootScope, $scope, $location,manageService) {
                $scope.tabs = [
                    {value: '/project_info', name: '项目信息',permissionCode : '0000200101-00'},
                    {value: '/project_role', name: '项目授权',permissionCode : '0000200101-00'},
                    {value: '/buildings_detail', name: '楼盘信息',permissionCode : '0000200102-00'},
                    {value: '/housetype_info', name: '户型信息',permissionCode : '0000200103-00'}
                ];
                $scope.current = $location.path();
                $rootScope.$on('$routeChangeSuccess', function () {
                    $scope.current = $location.path();
                });

                $scope.$watch('curProjectId',function(newValue,oldValue){
                    if(newValue !== oldValue){
                        $rootScope.curProjectId = newValue;
                        manageService.checkHasApp({},'&proj_id=' +newValue+'&app_code=5002').then(function(res){
                            if (res.data && res.data.retCode == 0){
                                var hasBindYdxs = res.data.data;
                                if(hasBindYdxs){//绑定移动销售才有房源信息Tab
                                    $scope.tabs = _.filter($scope.tabs,function(item){
                                        return item.value != '/sources_info';
                                    });
                                    $scope.tabs.push({value: '/sources_info', name: '房源信息',permissionCode : '0000200104-00'});
                                }else{
                                    $scope.tabs = _.filter($scope.tabs,function(item){
                                        return item.value != '/sources_info';
                                    });
                                    if($scope.current=='/sources_info'){
                                        $location.path('/project_info');
                                    }
                                }

                            }
                        });
                        if(newValue){
                            manageService.getProjInfo({},'&projectId=' +newValue).then(function(res){
                                if (res.data && res.data.retCode == 0){
                                    var projInfo = res.data.data && res.data.data.info;
                                    $scope.canEdit = projInfo.ifend;//ifend 0是非末级，1是末级
                                    $rootScope.$broadcast('changeCurProjectId',newValue,res);
                                }else{
                                    $rootScope.$broadcast('changeCurProjectId',newValue);
                                }
                            });
                        }
                    }
                });
                $scope.$watch('canEdit',function(newValue,oldValue){
                    if(newValue !== oldValue){
                        $rootScope.canEdit = newValue;
                        $rootScope.$broadcast('changeCanEdit',newValue);
                    }
                });

                var $tree = $("#proj_tree_table");
                $scope.isTreeCollapse = false;

                function fixedData(data) {
                    angular.forEach(data, function (item) {
                        item.children = item.childNodes;
                        item.name = item.name ? item.name : item.ProjName;
                        item.id = item.id ? item.id : item.p_projectId ;
                        fixedData(item.children);
                    });
                    return data;
                }

                function getFirstProjNode(data) {
                    if (data && data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            if (data[i].dataType == 2) {
                                return data[i];
                            } else if (data[i].childNodes && data[i].childNodes.length > 0) {
                                return getFirstProjNode(data[i].childNodes);
                            }
                        }
                    }
                }

                /**
                 * 过滤树数据
                 * @returns {*}
                 */

                function getFilterTreeData(data,key,value){
                    if (!data || !key) return [];
                    var result = [];
                    var value = value.toLowerCase();
                    for (var i = 0, l = data.length; i < l; i++) {
                        if (typeof data[i][key] == "string" && data[i][key].toLowerCase().indexOf(value)>-1) {
                            result.push(data[i]);
                            // 已包含子节点, 如果子节点也匹配value, 查询结果会多一个子节点
                            continue;
                        }
                        result = result.concat(getFilterTreeData(data[i]['children'], key, value));
                    }
                    return result;
                }


                $scope.toggleTreeCombo = function () {
                    // select cur node.
                    if(!$scope.isTreeCollapse && !$tree.tree('getSelectedNode')) {
                        $tree.tree('selectNode', $tree.tree('getNodeById', $scope.curProjectId));
                    }
                    $scope.isTreeCollapse = !$scope.isTreeCollapse;
                    $(window).on('click', function (event) {
                        var target = $(event.target);
                        if ($tree.parent().has(target).length < 1 && !target.is('#project_name')) {
                            $scope.isTreeCollapse = false;
                        }
                        $scope.$apply();
                    });
                };

                manageService.getProjectList()
                    .then(
                    function (res) {

                        var projectList = res.data.data;
                        $scope.projTreeData = fixedData(res.data.data);
                        $tree.tree({
                            data: $scope.projTreeData,
                            dragAndDrop: false,
                            useContextMenu: false,
                            autoOpen: 0, //展开级别
                            selectable: true,
                            onCreateLi: function (node, $li) {
                                if(node.dataType!=2){
                                    $li.find(".jqtree-element").addClass('notproj');
                                }
                                $li.data('tree-item-name',node.name);
                            },
                            //是否可以移动
                            onCanMove: function (node) {
                                return false;
                            },
                            //是否可以移动到
                            onCanMoveTo: function (moved_node, target_node, position) {
                                //只能在同级节点中移动
                                return false;
                            },
                            //移动句柄
                            onIsMoveHandle: function ($ele) {
                                return false;
                            }
                        }).on(
                            'tree.click',
                            function (event) {
                                var node = event.node;
                                if(node.dataType==2){
                                    $scope.curProject_name = node.name;
                                    $scope.curProjectId = node.id;
                                    $scope.isTreeCollapse = false;
                                    $scope.$apply();
                                } else {// dataType !== 2 不能选择
                                    return false;
                                }
                            }
                        );

                        $('input.search-box').keyup(function(){
                            var v = $(this).val();
                            var data = angular.copy($scope.projTreeData);
                            var filterData;
                            if (v) {
                                filterData = getFilterTreeData(data, 'name', v);
                                if (filterData.length < 1) {
                                    filterData = [{id: 'nodata', name: '无相关数据'}]
                                }
                            } else {
                                filterData = data;
                            }
                            $tree.tree('loadData',filterData);
                        });

                        $scope.projectList = projectList;
                        $scope.searchObj = util.getQueryParams(location.search);
                        if($scope.searchObj['projId']){
                            $scope.curProjectId = $scope.searchObj['projId'];
                            manageService.getProjInfo({},'&projectId=' + $scope.curProjectId).then(function(res){
                                if(res.data && res.data.retCode == 0){
                                    var projInfo = res.data.data && res.data.data.info;
                                    $scope.canEdit = projInfo.ifend;//ifend 0是非末级，1是末级
                                }
                            });
                            var cnode = $tree.tree('getNodeById',$scope.curProjectId)
                            $scope.curProject_name = cnode&&cnode.name;
                        }else{
                            var fnode = getFirstProjNode(projectList);
                            if(!fnode){
                                $rootScope.noProject = true;
                                $rootScope.$broadcast('noProject');
                            }
                            $scope.curProject_name = fnode ? fnode.name : '';
                            $scope.curProjectId = fnode ? fnode.id : '';
                        }
                        $scope.onShowCloneTips = function (item, dialog, dialogScope) {
                            dialog._$('content').css({height:280,overflowY:'auto',overflowX:'hidden',display:'block'})
                            $scope.targetProjectList = [];
                            dialogScope.projectList = _.filter($scope.projectList, function (item, value) {
                                item.selected = false;
                                if (item.p_projectId != $scope.curProjectId) {
                                    return true;
                                } else {
                                    dialogScope.clone_source = item;
                                    return false;
                                }
                            });
                            $scope.targetProjectList = dialogScope.projectList;
                        };

                        $scope.current = $location.path();
                    }
                );
            }
        ]);

    angular.bootstrap(document, ['app']);
});